<template>
  <div class="table-foreign-keys-panel">
    <div class="flex justify-between items-center mb-4">
      <h3 class="text-sm font-medium text-gray-700">外键约束</h3>
      <div class="flex space-x-2">
        <el-button size="small" @click="addForeignKey" type="success" plain class="hover:bg-green-50 transition-colors">
          <el-icon><Plus /></el-icon>添加外键
        </el-button>
      </div>
    </div>

    <div v-if="columns.length === 0" class="text-center py-8 bg-gray-50 rounded-lg border border-gray-200 shadow-sm">
      <p class="text-gray-500">请先添加表列，然后再创建外键</p>
    </div>
    <div v-else-if="foreignKeys.length === 0" class="text-center py-8 bg-gray-50 rounded-lg border border-gray-200 shadow-sm">
      <p class="text-gray-500">该表没有外键约束</p>
      <el-button size="small" type="primary" class="mt-4 hover:bg-blue-600 transition-colors" @click="addForeignKey">创建外键</el-button>
    </div>
    <div v-else class="overflow-x-auto rounded-lg shadow-sm border border-gray-200">
      <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50">
          <tr>
            <th scope="col" class="px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-left">约束名</th>
            <th scope="col" class="px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-left">源列</th>
            <th scope="col" class="px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-left">引用表</th>
            <th scope="col" class="px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-left">引用列</th>
            <th scope="col" class="px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-left">更新操作</th>
            <th scope="col" class="px-3 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider text-left">删除操作</th>
            <th scope="col" class="w-10 px-3 py-3 text-left"></th>
          </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
          <tr v-for="(fk, idx) in localForeignKeys" :key="idx" class="hover:bg-gray-50 transition-colors">
            <td class="px-3 py-3">
              <el-input v-model="fk.name" size="small" placeholder="约束名" @change="handleForeignKeysChange" 
                class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all" />
            </td>
            <td class="px-3 py-3">
              <el-select 
                v-model="fk.columns" 
                size="small" 
                style="width: 100%" 
                multiple 
                filterable 
                placeholder="选择源列" 
                @change="handleForeignKeysChange"
                class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all"
              >
                <el-option 
                  v-for="column in columns" 
                  :key="column.name" 
                  :label="column.name" 
                  :value="column.name" 
                />
              </el-select>
            </td>
            <td class="px-3 py-3">
              <div class="flex space-x-1">
                <el-select 
                  v-model="fk.referenceTable" 
                  size="small" 
                  style="width: 100%" 
                  filterable 
                  placeholder="引用表"
                  @change="(val) => handleReferenceTableChange(val, idx)"
                  class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all"
                >
                  <el-option 
                    v-for="table in availableTables" 
                    :key="table.name" 
                    :label="table.name" 
                    :value="table.name" 
                  />
                </el-select>
                <el-button size="small" circle @click="refreshTables"
                  class="hover:bg-gray-100 transition-colors">
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </div>
            </td>
            <td class="px-3 py-3">
              <el-select 
                v-model="fk.referenceColumns" 
                size="small" 
                style="width: 100%" 
                multiple 
                filterable 
                placeholder="引用列"
                :disabled="!fk.referenceTable"
                @change="handleForeignKeysChange"
                class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all"
              >
                <el-option 
                  v-for="column in getColumnsForTable(fk.referenceTable)" 
                  :key="column.name" 
                  :label="column.name" 
                  :value="column.name" 
                />
              </el-select>
            </td>
            <td class="px-3 py-3">
              <el-select 
                v-model="fk.updateRule" 
                size="small" 
                style="width: 100%" 
                @change="handleForeignKeysChange"
                class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all"
              >
                <el-option 
                  v-for="option in referentialActions" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </td>
            <td class="px-3 py-3">
              <el-select 
                v-model="fk.deleteRule" 
                size="small" 
                style="width: 100%" 
                @change="handleForeignKeysChange"
                class="hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all"
              >
                <el-option 
                  v-for="option in referentialActions" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </td>
            <td class="px-3 py-3">
              <el-button 
                type="danger" 
                size="small" 
                circle 
                plain
                @click="confirmRemoveForeignKey(idx)"
                class="hover:bg-red-50 transition-colors"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { Plus, Delete, Refresh } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus';
import { useDBServiceStore } from '@/stores/dbService';

const props = defineProps({
  foreignKeys: {
    type: Array,
    default: () => []
  },
  columns: {
    type: Array,
    default: () => []
  },
  configId: {
    type: String,
    required: false
  },
  connectionId: {
    type: String,
    required: false
  },
  databaseType: {
    type: String,
    default: 'mysql'
  },
  databaseConfigs: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['update', 'add', 'remove']);
const dbServiceStore = useDBServiceStore();

// 取得有效的连接ID (兼容 configId 和 connectionId)
const effectiveConnectionId = computed(() => {
  return props.connectionId || props.configId;
});

const localForeignKeys = ref([...props.foreignKeys]);
const availableTables = ref([]);
const tableColumns = ref({});
const isLoading = ref(false);

// 监听props变化
watch(() => props.foreignKeys, (newForeignKeys) => {
  localForeignKeys.value = [...newForeignKeys];
}, { deep: true });

// 获取默认的级联操作，根据数据库类型可能有所不同
const referentialActions = computed(() => {
  const actions = [
    { label: 'RESTRICT', value: 'RESTRICT' },
    { label: 'CASCADE', value: 'CASCADE' },
    { label: 'SET NULL', value: 'SET NULL' },
    { label: 'NO ACTION', value: 'NO ACTION' }
  ];
  
  // SQL Server特有的
  if (props.databaseType === 'sqlserver') {
    actions.push({ label: 'SET DEFAULT', value: 'SET DEFAULT' });
  }
  
  return actions;
});

// 组件挂载时加载表
onMounted(async () => {
  await refreshTables();
});

// 添加外键
const addForeignKey = () => {
  if (props.columns.length === 0) {
    ElMessageBox.alert('请先添加表列，然后再创建外键', '提示', {
      confirmButtonText: '确定'
    });
    return;
  }
  
  // 生成默认外键名
  const fkName = generateForeignKeyName();
  
  // 创建新外键
  const newForeignKey = {
    name: fkName,
    columns: [],
    referenceTable: '',
    referenceColumns: [],
    updateRule: 'RESTRICT',
    deleteRule: 'RESTRICT'
  };
  
  // 添加到本地外键
  localForeignKeys.value.push(newForeignKey);
  
  // 发送添加事件
  emit('add', newForeignKey);
};

// 生成外键名
const generateForeignKeyName = () => {
  const existingNames = localForeignKeys.value.map(fk => fk.name);
  let i = 1;
  let baseName = props.databaseType === 'sqlserver' ? 'FK_' : 'fk_';
  let name = `${baseName}${i}`;
  
  while (existingNames.includes(name)) {
    i++;
    name = `${baseName}${i}`;
  }
  
  return name;
};

// 确认删除外键
const confirmRemoveForeignKey = (index) => {
  const fkName = localForeignKeys.value[index].name || `外键 #${index + 1}`;
  
  ElMessageBox.confirm(`确定要删除外键 "${fkName}" 吗?`, '确认删除', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 发送删除事件
    emit('remove', index);
  }).catch(() => {
    // 用户取消操作
  });
};

// 刷新可用表列表
const refreshTables = async () => {
  try {
    isLoading.value = true;
    
    // 获取当前连接的数据库
    const currentConfig = props.databaseConfigs.find(config => config.id === effectiveConnectionId.value);
    if (!currentConfig) return;
    
    // 获取数据库中的表
    const tables = await dbServiceStore.listTables(effectiveConnectionId.value, currentConfig.database);
    availableTables.value = tables;
    
    // 清空已缓存的表列信息
    tableColumns.value = {};
    
    isLoading.value = false;
  } catch (error) {
    console.error('Error loading tables:', error);
    ElMessageBox.alert('加载表列表失败，请重试', '错误', {
      confirmButtonText: '确定',
      type: 'error'
    });
    isLoading.value = false;
  }
};

// 处理引用表变化
const handleReferenceTableChange = async (tableName, index) => {
  try {
    // 清空引用列
    localForeignKeys.value[index].referenceColumns = [];
    
    // 如果还没有加载该表的列
    if (!tableColumns.value[tableName]) {
      isLoading.value = true;
      
      // 获取当前连接的数据库
      const currentConfig = props.databaseConfigs.find(config => config.id === effectiveConnectionId.value);
      if (!currentConfig) return;
      
      // 获取表列信息
      const columns = await dbServiceStore.getTableColumns(
        effectiveConnectionId.value, 
        currentConfig.database, 
        tableName
      );
      
      // 缓存表列信息
      tableColumns.value[tableName] = columns;
      
      isLoading.value = false;
    }
    
    // 更新外键
    handleForeignKeysChange();
  } catch (error) {
    console.error('Error loading table columns:', error);
    ElMessageBox.alert('加载表列失败，请重试', '错误', {
      confirmButtonText: '确定',
      type: 'error'
    });
    isLoading.value = false;
  }
};

// 获取指定表的列
const getColumnsForTable = (tableName) => {
  if (!tableName) return [];
  return tableColumns.value[tableName] || [];
};

// 发送外键变更事件
const handleForeignKeysChange = () => {
  emit('update', [...localForeignKeys.value]);
};
</script>

<style scoped>
.table-foreign-keys-panel {
  padding: 16px 0;
}

:deep(.el-input__wrapper) {
  @apply shadow-none;
}

:deep(.el-input__wrapper:hover) {
  @apply border-gray-400;
}

:deep(.el-input__wrapper.is-focus) {
  @apply border-blue-500 ring-1 ring-blue-500;
}

:deep(.el-select .el-input__wrapper) {
  @apply shadow-none;
}

:deep(.el-select-dropdown__item) {
  @apply text-sm py-2;
}

:deep(.el-tag) {
  @apply text-xs bg-blue-50 border-blue-100 text-blue-600;
}

:deep(.el-tag .el-tag__close) {
  @apply text-blue-400 hover:bg-blue-500 hover:text-white;
}

:deep(.el-button.is-disabled) {
  @apply opacity-50 cursor-not-allowed;
}
</style> 